const Topic = require('../models/topic')
const Question = require('../models/question')

class TopicController {
  // ===================话题列表==================
  async getTopiclist(ctx) {
    // 分页逻辑
    let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
    // 防止输入负数
    perPage = Math.max(perPage * 1, 1) 
    page = Math.max(page * 1,1) 

    const topicList = await Topic.find({
      name: new RegExp(ctx.query.q)
    }).limit(perPage).skip((page-1) * perPage)  // limit限制查询数量、skip跳过多少条记录
    ctx.body = topicList
  }

  // ====================查找特定话题==============
  async getTopic(ctx) {
    const fields = ctx.query.fields || ''
    const selectFields = fields.split(';').filter(item=>item).map(item=> ' +'+item).join('')
    const topic = await Topic.findById(ctx.params.id).select(selectFields)
    ctx.body = topic
  }

  // ===================创建话题==============
  async createTopic(ctx) {
    ctx.verifyParams({
      name: {type: 'string', required: true},
      avatar_url: {type: 'string', required: false},
      introduction: {type: 'string', required: false}
    })
    // 不允许重复创建相同的话题
    const isExist = await Topic.findOne({name: ctx.request.body.name})
    if(!isExist) {
      const topic  = await Topic(ctx.request.body).save()
      ctx.body = topic
    }
    ctx.status = 204
  }

  // ===================修改话题==============
  async updateTopic(ctx) {
    ctx.verifyParams({
      name: {type: 'string', required: false},
      avatar_url: {type: 'string', required: false},
      introduction: {type: 'string', required: false}
    })
    const topic  = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body,{new: true}).select('+introduction')
    // 返回更新结果
    ctx.body = topic
  }

  // ===================话题相关的问题=============
  async listQuestion(ctx) {
    // 分页逻辑
    // let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
    // 防止输入负数
    // perPage = Math.max(perPage * 1, 1) 
    // page = Math.max(page * 1,1) 

    // 问题列表
    const questionList = await Question.find({topics: ctx.params.id})
    ctx.body = questionList
  }
}

module.exports = new TopicController()

